<template>
  <AppDialogForm
    :title="props.roleInfo.id ? '编辑角色' : '添加角色'"
    :confirm="handleSubmit"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="loading"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input
          v-model="formData.roleDesc"
          placeholder="请输入角色描述"
          :rows="2"
          type="textarea"
        />
      </el-form-item>
    </el-form>
  </AppDialogForm>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { addRoles, editRoles } from "@/api/roles.js";

const props = defineProps({
  roleInfo: {
    type: Object,
    default: () => {},
  },
});
const emit = defineEmits(["success"]);
const form = ref(null);
const loading = ref(false);
const formData = ref({
  roleName: "",
  roleDesc: "",
});

const formRules = {
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  roleDesc: [{ required: true, message: "请输入角色描述", trigger: "blur" }],
};

const loadInfo = () => {
  if (!props.roleInfo) {
    return;
  }
  formData.value = { ...props.roleInfo };
};

const handleDialogOpen = () => {
  loadInfo();
};

const handleSubmit = async () => {
  const valid = await form.value.validate();
  if (!valid) {
    return;
  }
  loading.value = true;
  if (props.roleInfo.id) {
    // 更新用户
    await editRoles(formData.value).finally(() => {
      loading.value = false;
    });
    ElMessage.success("编辑角色成功");
  } else {
    // 添加用户
    await addRoles(formData.value).finally(() => {
      loading.value = false;
    });
    ElMessage.success("添加角色成功");
  }
  emit("success");
};
const handleDialogClosed = () => {
  form.value.clearValidate(); // 清除验证结果
  form.value.resetFields(); // 清除表单数据
  formData.value = {
    roleName: "",
    roleDesc: "",
  };
};
</script>

<style lang="scss" scoped></style>
